package terrain;

import java.io.IOException;
import java.io.InputStream;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.FloatBuffer;

import javax.microedition.khronos.opengles.GL10;

import system.Graphics;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.opengl.GLUtils;

public class TerrainTexture {
	private int[] textures = new int[1];
	private float m_fWidth;
	private float m_fHeight;
	private FloatBuffer _textureBuffer;
	
	public float texture[] = {    		
    		//Mapping coordinates for the vertices		
			0.0f, 0.0f,		// Point 2       -- Top Right
			0.0f, 1.0f,		// Point 3		 -- Top Left
			1.0f, 1.0f,		// Point 0  	 -- Bottom Left
			1.0f, 0.0f		// Point 1 		 -- Bottom Right
	};
	
	public TerrainTexture(InputStream is){
		GL10 gl = Graphics.GetGraphics();
		Bitmap bitmap = null;
		try {
			//BitmapFactory is an Android graphics utility for images
			bitmap = BitmapFactory.decodeStream(is);
			
			m_fWidth = bitmap.getWidth();
			m_fHeight = bitmap.getHeight();
			
		} finally {			//Always clear and close
			try {
				is.close();
				is = null;
			} 
			catch (IOException e) {
			}
		}
		
		gl.glGenTextures(1, textures, 0);
		gl.glBindTexture(GL10.GL_TEXTURE_2D, textures[0]);
		gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_MIN_FILTER, GL10.GL_NEAREST);
		gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_MAG_FILTER, GL10.GL_LINEAR);

		gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_WRAP_S, GL10.GL_REPEAT);
		gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_WRAP_T, GL10.GL_REPEAT);
	
		GLUtils.texImage2D(GL10.GL_TEXTURE_2D, 0, bitmap, 0);
		//Clean up
		bitmap.recycle();
//		
		ByteBuffer byteBuf = ByteBuffer.allocateDirect(texture.length * 4);
		byteBuf.order(ByteOrder.nativeOrder());
		_textureBuffer = byteBuf.asFloatBuffer();
		_textureBuffer.put(texture);
		_textureBuffer.position(0);
		gl.glTexCoordPointer(2, GL10.GL_FLOAT, 0, _textureBuffer);
	}
	
	public void Binding(GL10 gl){
		gl.glEnable(GL10.GL_TEXTURE_2D);
		_textureBuffer.position(0);
		gl.glEnableClientState(GL10.GL_TEXTURE_COORD_ARRAY);
		gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_MIN_FILTER, GL10.GL_NEAREST);
		gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_MAG_FILTER, GL10.GL_LINEAR);

//		gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_WRAP_S, GL10.GL_REPEAT);
//		gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_WRAP_T, GL10.GL_REPEAT);
		gl.glTexEnvf(GL10.GL_TEXTURE_ENV, GL10.GL_TEXTURE_ENV_MODE, GL10.GL_MODULATE);
		gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_MAG_FILTER, GL10.GL_LINEAR);
		gl.glBindTexture(GL10.GL_TEXTURE_2D, textures[0]);
	}
	
	public void Unbinding(GL10 gl){
		gl.glDisable(GL10.GL_TEXTURE_2D);
		gl.glBindTexture(GL10.GL_TEXTURE_2D, 0);
	}
	
	
}
